<template>
  <el-dialog
    v-el-drag-dialog
    :title="type === 'add' ? '新增车辆' : '编辑车辆'"
    :visible.sync="visible"
    width="700px"
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :rules="rules" :model="temp" label-position="right" label-width="90px">
      <el-form-item label="车牌号" prop="truckCode">
        <el-input v-model="temp.truckCode" :disabled="type !== 'add'" :maxlength="20" clearable placeholder="请输入" />
      </el-form-item>
      <el-form-item label="车辆编号" prop="truckNum">
        <el-input v-model="temp.truckNum" :maxlength="20" clearable placeholder="请输入" />
      </el-form-item>
      <el-form-item label="所属机构" prop="orgSNNo">
        <el-tree-select
          v-model="temp.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
        />
      </el-form-item>
      <el-form-item label="责任归属" prop="revertBelong">
        <el-select v-model="temp.revertBelong" filterable placeholder="请选择" style="width: 100%;">
          <el-option
            v-for="item in revertBelongList"
            :key="item.value"
            :label="item.keyName"
            :value="item.keyVal"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="车辆类型" prop="truckType">
        <el-select v-model="temp.truckType" filterable placeholder="请选择" style="width: 100%;" @change="truckTypeChange">
          <el-option
            v-for="item in truckTypeList"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="生产厂家" prop="manufacturer">
        <el-input v-model="temp.manufacturer" :maxlength="20" clearable placeholder="请输入" />
      </el-form-item>
      <el-form-item label="车辆属性" prop="attributes">
        <el-select v-model="temp.attributes" filterable placeholder="请选择" style="width: 100%;">
          <el-option
            v-for="item in attributesList"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="荷载瓶数" prop="loadNum">
        <el-input v-model="temp.loadNum" :maxlength="20" />
      </el-form-item>
      <el-form-item label="车载GPS" prop="gpsInstall">
        <el-select v-model="temp.gpsInstall" filterable placeholder="请选择" style="width: 100%;">
          <el-option
            v-for="item in gpsInstallList"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="车载视频" prop="videoInstall">
        <el-select v-model="temp.videoInstall" filterable placeholder="请选择" style="width: 100%;">
          <el-option
            v-for="item in videoInstallList"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="随车司机" prop="driver">
        <el-input v-model="temp.driver" readonly>
          <el-button v-if="!temp.driver" slot="append" class="append-search" @click="openDriverman('司机', temp.truckType)">获取</el-button>
          <el-button v-else slot="append" class="append-search" @click.prevent="clearDriverman('司机')">清除</el-button>
        </el-input>
      </el-form-item>
      <el-form-item v-show="temp.truckType === 3" label="随车押运员" prop="escortName">
        <el-input v-model="temp.escortName" readonly>
          <el-button v-if="!temp.escortName" slot="append" class="append-search" @click="openDriverman('押送员', temp.truckType)">获取</el-button>
          <el-button v-else slot="append" class="append-search" @click.prevent="clearDriverman('押运员')">清除</el-button>
        </el-input>
      </el-form-item>
      <el-form-item prop="remark">
        <label slot="label">备注</label>
        <el-input v-model="temp.remark" type="textarea" :rows="3" :maxlength="50" show-word-limit />
      </el-form-item>
      <el-form-item label="车辆照片" prop="photo">
        <el-upload
          ref="upload"
          class="avatar-uploader"
          action="//upload.qiniup.com/"
          accept=".bmp, .gif, .jpg, .jpeg, .png, image/bmp, image/gif, image/jpg, image/jpeg, image/png"
          :data="qiniuPhoto"
          :show-file-list="false"
          :on-success="(res, file)=>handleAvatarSuccess(res, file)"
          :before-upload="(file)=>beforeAvatarUpload(file)"
        >
          <img v-if="temp.photo" :src="temp.photo" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
    </el-form>
    <driverMan ref="driverMan" :tree-data="treeData" />
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button :loading="$loadingPlugin.add || $loadingPlugin.edit" type="primary" @click="success">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { vehicleAdd, queryQiniuyunUploadToken, presetDicQueryList } from '@/api'
  import { mapGetters } from 'vuex'
  import driverMan from './driverMan'
  import { imgBaseUrl } from '@/utils/config'
  export default {
    name: 'add-vehicle',
    components: { driverMan },
    props: {
      treeData: {
        type: Array,
        required: true
      }
    },
    data() {
      // const validateTruckCode = (rule, value, callback) => {
      //   if (!value) {
      //     callback(new Error('请输入车牌号'))
      //   } else {
      //     if (value !== '') {
      //       const reg = new RegExp('^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$')
      //       if (!reg.test(value)) {
      //         callback(new Error('请输入有效的车牌号'))
      //       }
      //     } else {
      //       callback()
      //     }
      //     callback()
      //   }
      // }
      return {
        imgBaseUrl,
        visible: false,
        type: 'add',
        temp: {
          truckCode: '',
          truckNum: '',
          revertBelong: '',
          orgSNNo: '',
          truckType: '',
          loadNum: '',
          driver: '',
          driverId: '',
          remark: '',
          photo: '',
          attributes: '',
          gpsInstall: '',
          videoInstall: '',
          manufacturer: '',
          escortName: '',
          escortId: ''
        },
        qiniuPhoto: {
          key: '', // 图片名字处理
          token: '', // 七牛云token
          data: {},
          bucket: ' '
        },
        oldTruckCode: '',
        revertBelongList: [],
        truckTypeList: [
          {
            value: 1,
            desc: '三轮车'
          },
          {
            value: 2,
            desc: '两轮车'
          },
          {
            value: 3,
            desc: '危化品运输车'
          }
        ],
        attributesList: [
          {
            value: 1,
            desc: '燃油车'
          },
          {
            value: 2,
            desc: '电动车'
          }
        ],
        gpsInstallList: [
          {
            value: 1,
            desc: '已安装'
          },
          {
            value: 0,
            desc: '未安装'
          }
        ],
        videoInstallList: [
          {
            value: 1,
            desc: '已安装'
          },
          {
            value: 0,
            desc: '未安装'
          }
        ],
        rules: {
          // truckCode: [{ required: true, message: '请输入车牌号', trigger: 'blur' }, { validator: validateTruckCode, trigger: 'blur' }],
          truckCode: [{ required: true, message: '请输入车牌号', trigger: 'blur' }],
          orgSNNo: [{ required: true, message: '请选择所属单位', trigger: 'change' }],
          truckType: [{ required: true, message: '请选择车型信息', trigger: 'change' }],
          revertBelong: [{ required: true, message: '请选择责任归属', trigger: 'change' }],
          truckNum: [{ required: true, message: '请输入车辆编号', trigger: 'blur' }],
          attributes: [{ required: true, message: '请选择车辆属性', trigger: 'change' }],
          gpsInstall: [{ required: true, message: '请选择车载GPS', trigger: 'change' }],
          videoInstall: [{ required: true, message: '请选择车载视频', trigger: 'change' }]
        },
        orgSNNo: ''
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    methods: {
      open(temp) {
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          this.getQiniuyunUploadToken()
          if (temp) {
            this.temp = { ...temp }
            console.log(this.temp)
            if (!this.temp.attributes) {
              this.temp.attributes = ''
            }
            this.oldTruckCode = temp.truckCode
            this.type = 'edit'
            this.rules.truckCode[0].required = false
            this.oldTruckType = this.temp.truckType
          } else {
            this.rules.truckCode[0].required = true
          }
        })
      },
      // 获取七牛云上传token
      async getQiniuyunUploadToken() {
        const res = await queryQiniuyunUploadToken()
        const res1 = await presetDicQueryList({ keyFun: 301, keyPro: 2, keyStatus: 2 })
        this.revertBelongList = res1.data
        this.qiniuPhoto.token = res.data
      },
      handleAvatarSuccess(res) {
        this.temp.photo = imgBaseUrl + res.key
      },
      beforeAvatarUpload(file) {
        const key = `${this.temp.truckCode}_${new Date().getTime()}_${file.name}`
        this.qiniuPhoto.key = key
        return this.qiniuPhoto
      },
      truckTypeChange(type) {
        if (type === 1 || type === 2) {
          if (this.oldTruckType === 3) {
            this.clearDriverman('司机')
          }
        }
        if (type === 3) {
          if (this.oldTruckType === 1 || this.oldTruckType === 2) {
            this.clearDriverman('司机')
          }
        }
        this.oldTruckType = type
      },
      async openDriverman(type, truckType) {
        const res = await this.$refs.driverMan.open(type, truckType, this.orgSNNo)
        if (type === '司机') {
          this.currentDriverMan = res
          this.$set(this.temp, 'driver', res.userName)
          this.orgSNNo = res.orgSNNo
          this.clearDriverman('随车押运员')
        } else {
          this.currentEscortMan = res
          this.$set(this.temp, 'escortName', res.userName)
        }
      },
      clearDriverman(type) {
        if (type === '司机') {
          this.currentDriverMan = null
          this.$set(this.temp, 'driver', '')
          this.$set(this.temp, 'driverId', '')
          this.orgSNNo = ''
          this.$set(this.temp, 'escortName', '')
          this.$set(this.temp, 'escortId', '')
          this.$set(this.temp, 'currentEscortMan', null)
        } else {
          this.currentEscortMan = null
          this.$set(this.temp, 'escortName', '')
          this.$set(this.temp, 'escortId', '')
        }
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          const params = { ...this.temp }
          const currentOrg = this.orgList.find(item => item.orgSNNo === this.temp.orgSNNo)
          params.orgId = currentOrg.orgId
          params.orgName = currentOrg.orgName
          params.driverId = this.currentDriverMan ? this.currentDriverMan.userId : this.temp.driverId
          if (this.temp.truckType === 3) {
            params.escortId = this.currentEscortMan ? this.currentEscortMan.userId : this.temp.escortId
          }
          if (this.type === 'add') {
            this.add(params)
          } else {
            this.edit(params)
          }
        })
      },
      async add(params) {
        await vehicleAdd(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '新增成功',
          type: 'success',
          duration: 2000
        })
      },
      async edit(params) {
        await vehicleAdd({
          ...params,
          oldTruckCode: this.oldTruckCode
        })
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      },
      reset() {
        this.type = 'add'
        this.temp = {
          truckCode: '',
          truckNum: '',
          revertBelong: '',
          orgSNNo: '',
          truckType: '',
          loadNum: '',
          driver: '',
          driverId: '',
          remark: '',
          escortName: '',
          escortId: ''
        }
        this.currentDriverMan = null
        this.currentEscortMan = null
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 50%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
.info-title {
  display: flex;
  align-items: center;
  margin-top: 10px;
  margin-bottom: 20px;
  .title-icon {
    display: inline-block;
    width: 4px;
    height: 18px;
    margin-right: 6px;
    background: $themeColor;
  }
  span {
    font-weight: 700;
    color: $themeColor;
  }
}
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}
.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  line-height: 178px;
  color: #8c939d;
  text-align: center;
}
.avatar {
  display: block;
  width: 178px;
  height: 178px;
}
</style>
